package com.ehotting.eaf.core.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

public class KeyGenerator {

    /**
     * 生成RSA密钥对
     * @return
     */
    public static KeyDto generate(){
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024);
            KeyPair keyPair = keyPairGenerator.genKeyPair();
            RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate();
            byte[] privateKey = Base64.getEncoder().encode(priKey.getEncoded());
            byte[] publicKey = Base64.getEncoder().encode(pubKey.getEncoded());
            return new KeyDto(new String(publicKey),new String(privateKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("生成密钥对失败！");
            return null;
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class KeyDto{
        private String pubStr;
        private String priStr;
    }
}
